const express = require('express');
const router = express.Router();
const db = require('../db/index');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const jwt_config = require('../jwt_config/index');

// 注册接口
router.post('/register', (req, res) => {
    const reginfo = req.body;
    if (!reginfo.account || !reginfo.password) {
        return res.send({ status: 1, message: '用户名或密码不能为空' });
    }
    
    const sql = `select * from users where account = ?`;
    db.query(sql, reginfo.account, (err, results) => {
        if (err) return res.send({ status: 1, message: err.message });
        if (results.length > 0) return res.send({ status: 1, message: '用户名已存在' });
        
        const create_time = Date.now();
        const saltPassword = reginfo.password + create_time;
        const hashedPassword = bcrypt.hashSync(saltPassword, 10);
        
        db.query(`insert into users set ?`, {
            account: reginfo.account,
            password: hashedPassword,
            name: reginfo.name,
            sex: reginfo.sex,
            cpid: null,
            create_time: create_time
        }, (err, results) => {
            if (err) return res.send({ status: 1, message: err.message });
            results.affectedRows === 1 
                ? res.send({ status: 200, message: '注册成功' })
                : res.send({ status: 1, message: '注册失败' });
        });
    });
});

// 登录接口
router.post('/login', (req, res) => {
    const login_info = req.body;
    const sql = 'select * from users where account=?';
    
    db.query(sql, login_info.account, (err, results) => {
        if(err) return res.cc(err);
        if(results.length !== 1) return res.cc('用户名或密码错误');
        
        const compareResult = bcrypt.compareSync(
            login_info.password + results[0].create_time, 
            results[0].password
        );
        if (!compareResult) return res.cc('用户名或密码错误');
        
        const user = {
            ...results[0],
            password: '',
            create_time: '',
        };
        
        const tokenStr = jwt.sign(user, jwt_config.jwtSecretKey, {
            expiresIn: '3h'
        });
        
        res.send({
            user,
            status: 200,
            message: '登录成功',
            token: 'Bearer ' + tokenStr,
        });
    });
});

router.get("/userInfo/:userId", (req,res) =>{
    console.log(req.params.userId)
    res.send({
        status: 200,
        message: "获取成功",
        req: req.params.userId
    })
})
module.exports = router;

